/*
 * JSMuffin - Another javascript canvas framework.
 * @author xshifty
 */

var muffin = muffin || {
	DOM:document,
	VERSION:'0.1a',
	load:function (script_) {
		var scripts = muffin.DOM.tag('script');
		var path = null;
		
		for (var i in scripts) if (scripts[i].getAttribute('src').indexOf('muffin.js') > -1) {
			path = scripts[i].getAttribute('src').split('muffin.js')[0];
			break;
		}
		
		path = [path, 'muffin', script_+'.js'].join('/').replace('/\/{2,}/g', '/');
		
		muffin.DOM.write('<script type="text/javascript" src="'+path+'"></script>');
	},
	Class:function (prototype_) {
		var class_ = function () {
			this.init.apply(this, arguments);
		};
		class_.prototype = prototype_;
		class_.prototype.__MUFFIN_OBJECT__ = true;
		return class_;
	},
	extend:function () {
		if (arguments.length > 1) {
			for (var i = 1; i < arguments.length; i++) {
				if (typeof arguments[i] == 'object')
					if (typeof arguments[0] == 'function') {
						arguments[0].prototype = arguments[i];
					} else {
						for (j in arguments[i]) {
							arguments[0][j] = arguments[i][j];
						}
					}
			}
			return arguments[0];
		}
	},
	clone:function (object_) {
		return muffin.extend({}, object_);
	}
};

muffin.DOM.id = function (id_, container_) {
	var container = container_ || muffin.DOM; 
	return container.getElementById(id_);
};

muffin.DOM.tag = function (tagName_, container_) {
	var container = container_ || muffin.DOM;
	return container.getElementsByTagName(tagName_);
};

muffin.DOM.create = function (html_) {
	var container = muffin.DOM.createElement('span');
	container.innerHTML = html_;
	return muffin.DOM.tag('*', container)[0] || muffin.DOM.all[0];
};

muffin.DOM.event = function (type_, element_, callback_) {
	if (!element_.__MUFFIN_OBJECT__) {
		try {
			element_.addEventListener(type_, callback_, true);
		} catch (e) {
			try {
				element_.attachEvent('on'+type_, callback_);
			} catch (ee) {
				try {
					element_['on'+type_] = callback_;
				} catch (E) {}
			}
		}
	} else {
		element_.events['on'+type_] = callback_;
	}
};

muffin.DOM.offset = function (element_) {
	var element = element_ || {};
	var elemBounds = element.getBoundingClientRect ? element.getBoundingClientRect() : {'top':0,'left':0};
	var clientBounds = {
		'top':muffin.DOM.documentElement.clientTop || muffin.DOM.body.clientTop || 0,
		'left':muffin.DOM.documentElement.leftTop || muffin.DOM.body.leftTop || 0
	};
	var winBounds = {
		'top':window.pageYOffset || muffin.DOM.scrollLeft || muffin.DOM.body.scrollLeft,
		'left':window.pageXOffset || muffin.DOM.scrollTop || muffin.DOM.body.scrollTop
	};
	
	return {'top':elemBounds.top + winBounds.top - clientBounds.top,'left':elemBounds.left + winBounds.left - clientBounds.left};
};